package network.server.handler.CourseHandler;

import com.alibaba.fastjson.JSON;
import common.model.Entity.courseEntity.Course;
import common.model.Entity.courseEntity.CourseLocation;
import common.util.JsonUtil;
import module.course.CourseService;
import module.course.impl.CourseServiceImpl;
import network.protocol.Request;
import network.protocol.Response;
import network.server.RequestHandler;

import java.util.Map;

public class CourseHandler implements RequestHandler {
    private final CourseService courseService = CourseServiceImpl.getInstance();

    @Override
    public Response<?> handle(Request req) {
        String action = req.getAction();
        Map<String, Object> params = req.getParams();

        // 从action中提取具体的方法名
        String methodName = action.substring(action.indexOf('.') + 1);

        // 课程相关操作
        switch (methodName) {
            // 课程操作
            case "findById":
                return handleFindById(params);
            case "findAll":
                return handleFindAll();
            case "findByName":
                return handleFindByName(params);
            case "findStatusTrue":
                return handleFindStatusTrue();
            case "findByCourseCode":
                return handleFindByCourseCode(params);
            case "create":
                return handleCreateCourse(params);
            case "update":
                return handleUpdateCourse(params);
            case "delete":
                return handleDeleteCourse(params);
            case "enrollStudent":
                return handleEnrollStudent(params);
            case "dropStudent":
                return handleDropStudent(params);
            case "findStudents":
                return handleFindStudentsByCourseId(params);
            case "apply":
                return handleApplyCourse(params);
            case "updateMyCourse":
                return handleUpdateMyCourse(params);
            case "findByTeacher":
                return handleFindCoursesByTeacher(params);
            case "schedule":
                return handleScheduleCourse();
            case "findSelectedCourseByStudentId":
                return handleFindSelectedCourseByStudentId(params);
            case "findCourseWithSchedule":
                return handleFindCourseWithSchedule(params);
            case "findTeacherNameByTeacherId":
                return handleFindTeacherNameByTeacherId(params);

            // 教室位置操作
            case "findLocationById":
                return handleFindLocationById(params);
            case "insertLocation":
                return handleInsertLocation(params);
            case "findAllLocation":
                return handleFindAllLocation();
            case "updateLocation":
                return handleUpdateLocation(params);
            case "deleteLocation":
                return handleDeleteLocation(params);
            case "findLocationByBuilding":
                return handleFindLocationByBuilding(params);
            case "findLocationByRoomNumber":
                return handleFindLocationByRoomNumber(params);
            case "findLocationByBuildingAndRoom":
                return handleFindLocationByBuildingAndRoom(params);
            case "getLocationCount":
                return handleGetLocationCount();

            default:
                return Response.error(404, "未知的操作: " + methodName);
        }
    }

    // 原有的课程操作方法保持不变...
    private Response<?> handleFindById(Map<String, Object> params) {
        try {
            Long id = Long.parseLong(params.get("id").toString());
            return courseService.findById(id);
        } catch (Exception e) {
            return Response.error("参数解析失败: " + e.getMessage());
        }
    }

    private Response<?> handleFindAll() {
        return courseService.findAll();
    }

    private Response<?> handleFindByName(Map<String, Object> params) {
        try {
            String name = params.get("name").toString();
            return courseService.findByName(name);
        } catch (Exception e) {
            return Response.error("参数解析失败: " + e.getMessage());
        }
    }

    private Response<?> handleFindTeacherNameByTeacherId(Map<String,Object> params){
        try{
            Long id = Long.parseLong(params.get("id").toString());
            return courseService.findTeacherNameByTeacherId(id);
        }catch (Exception e){
            return Response.error("参数解析失败: " + e.getMessage());
        }
    }

    private Response<?> handleFindCourseWithSchedule(Map<String,Object> params){
        try{
            Long id = Long.parseLong(params.get("id").toString());
            return courseService.findCourseWithSchedule(id);
        }catch (Exception e){
            return Response.error("参数解析失败: " + e.getMessage());
        }
    }

    private Response<?> handleCreateCourse(Map<String, Object> params) {
        try {
            Course course = JsonUtil.fromJson(JsonUtil.toJson(params), Course.class);
            return courseService.createCourse(course);
        } catch (Exception e) {
            return Response.error("课程参数解析失败: " + e.getMessage());
        }
    }

    private Response<?> handleUpdateCourse(Map<String, Object> params) {
        try {
            Course course = JsonUtil.fromJson(JsonUtil.toJson(params), Course.class);
            return courseService.updateCourse(course);
        } catch (Exception e) {
            return Response.error("课程参数解析失败: " + e.getMessage());
        }
    }

    private Response<?> handleDeleteCourse(Map<String, Object> params) {
        try {
            Long id = Long.parseLong(params.get("id").toString());
            return courseService.deleteCourse(id);
        } catch (Exception e) {
            return Response.error("参数解析失败: " + e.getMessage());
        }
    }

    private Response<?> handleEnrollStudent(Map<String, Object> params) {
        try {
            Long courseId = Long.parseLong(params.get("courseId").toString());
            Long studentId = Long.parseLong(params.get("studentId").toString());
            return courseService.enrollStudent(courseId, studentId);
        } catch (Exception e) {
            return Response.error("参数解析失败: " + e.getMessage());
        }
    }

    private Response<?> handleDropStudent(Map<String, Object> params) {
        try {
            Long courseId = Long.parseLong(params.get("courseId").toString());
            Long studentId = Long.parseLong(params.get("studentId").toString());
            return courseService.dropStudent(courseId, studentId);
        } catch (Exception e) {
            return Response.error("参数解析失败: " + e.getMessage());
        }
    }

    private Response<?> handleFindSelectedCourseByStudentId(Map<String,Object> params){
        try {
            Long studentId = Long.parseLong(params.get("studentId").toString());
            return courseService.findSelectedCourseByStudentId(studentId);
        } catch (Exception e) {
            return Response.error("参数解析失败: " + e.getMessage());
        }
    }

    private Response<?> handleFindStudentsByCourseId(Map<String, Object> params) {
        try {
            Long courseId = Long.parseLong(params.get("courseId").toString());
            return courseService.findStudentsByCourseId(courseId);
        } catch (Exception e) {
            return Response.error("参数解析失败: " + e.getMessage());
        }
    }

    private Response<?> handleApplyCourse(Map<String, Object> params) {
        try {
            Course course = JsonUtil.fromJson(JsonUtil.toJson(params), Course.class);
            // 验证课程对象的基本字段
            if (course.getCourseCode() == null || course.getCourseCode().trim().isEmpty()) {
                return Response.error("课程代码不能为空");
            }
            if (course.getCourseName() == null || course.getCourseName().trim().isEmpty()) {
                return Response.error("课程名称不能为空");
            }
            return courseService.applyCourse(course);
        } catch (Exception e) {
            return Response.error("课程参数解析失败: " + e.getMessage());
        }
    }

    private Response<?> handleUpdateMyCourse(Map<String, Object> params) {
        try {
            Long teacherId = Long.parseLong(params.get("teacherId").toString());

            Map<String, Object> courseParams = JSON.parseObject(JSON.toJSONString(params));
            courseParams.remove("teacherId");

            Course course = JsonUtil.fromJson(JsonUtil.toJson(courseParams), Course.class);
            return courseService.updateMyCourse(teacherId, course);
        } catch (Exception e) {
            return Response.error("参数解析失败: " + e.getMessage());
        }
    }

    private Response<?> handleFindCoursesByTeacher(Map<String, Object> params) {
        try {
            String teacherName = params.get("teacherName").toString();
            return courseService.findCoursesByTeacher(teacherName);
        } catch (Exception e) {
            return Response.error("参数解析失败: " + e.getMessage());
        }
    }

    private Response<?> handleScheduleCourse() {
        return courseService.scheduleCourse();
    }

    // ========== 教室位置相关方法 ==========

    private Response<?> handleFindLocationById(Map<String, Object> params) {
        try {
            Long id = Long.parseLong(params.get("id").toString());
            return courseService.findLocationById(id);
        } catch (Exception e) {
            return Response.error("参数解析失败: " + e.getMessage());
        }
    }

    private Response<?> handleInsertLocation(Map<String, Object> params) {
        try {
            CourseLocation location = JsonUtil.fromJson(JsonUtil.toJson(params), CourseLocation.class);
            return courseService.insertNewLocation(location);
        } catch (Exception e) {
            return Response.error("教室位置参数解析失败: " + e.getMessage());
        }
    }

    private Response<?> handleFindAllLocation() {
        return courseService.findAllLocation();
    }

    private Response<?> handleUpdateLocation(Map<String, Object> params) {
        try {
            Map<String, Object> originMap = (Map<String, Object>) params.get("originLocation");
            Map<String, Object> newMap = (Map<String, Object>) params.get("newLocation");

            CourseLocation originLocation = JsonUtil.fromJson(JsonUtil.toJson(originMap), CourseLocation.class);
            CourseLocation newLocation = JsonUtil.fromJson(JsonUtil.toJson(newMap), CourseLocation.class);

            return courseService.updateLocation(originLocation, newLocation);
        } catch (Exception e) {
            return Response.error("教室位置参数解析失败: " + e.getMessage());
        }
    }

    private Response<?> handleDeleteLocation(Map<String, Object> params) {
        try {
            CourseLocation location = JsonUtil.fromJson(JsonUtil.toJson(params), CourseLocation.class);
            return courseService.deleteLocation(location);
        } catch (Exception e) {
            return Response.error("教室位置参数解析失败: " + e.getMessage());
        }
    }

    private Response<?> handleFindLocationByBuilding(Map<String, Object> params) {
        try {
            String building = params.get("building").toString();
            return courseService.findByBuilding(building);
        } catch (Exception e) {
            return Response.error("参数解析失败: " + e.getMessage());
        }
    }

    private Response<?> handleFindLocationByRoomNumber(Map<String, Object> params) {
        try {
            String roomNumber = params.get("roomNumber").toString();
            return courseService.findByRoomNumber(roomNumber);
        } catch (Exception e) {
            return Response.error("参数解析失败: " + e.getMessage());
        }
    }

    private Response<?> handleFindLocationByBuildingAndRoom(Map<String, Object> params) {
        try {
            String building = params.get("building").toString();
            String roomNumber = params.get("roomNumber").toString();
            return courseService.findByBuildingAndRoomNumber(building, roomNumber);
        } catch (Exception e) {
            return Response.error("参数解析失败: " + e.getMessage());
        }
    }

    private Response<?> handleGetLocationCount() {
        return courseService.getLocationCount();
    }

    private Response<?> handleFindByCourseCode(Map<String,Object> params){
        try{
            String code = params.get("courseCode").toString();
            return courseService.findByCode(code);
        }catch (Exception e){
            return Response.error("courseCode参数解析失败: " + e.getMessage());
        }
    }

    private Response<?> handleFindStatusTrue() {
        return courseService.findStatusTrue();
    }
}